<template>
  <view class="publish-activity-page">
    <!-- 头部区域：返回按钮 + 页面标题 -->
    <my-navbar title="发布活动" leftIcon="arrow-left" bgColor="#4facfe" :custom="false" :autoBack="true"
            		titleStyle="color:#ffffff" leftIconColor="#ffffff" leftIconSize="40"></my-navbar>


    <!-- 大图上传 -->
	<view class="scene-title">展示效果图</view>
    <view class="big-img-upload">
      <text class="tip">封面效果图-限1张</text>
	  <view 
	          class="add-small-img" 
	          @click="selectBigImg"
	          v-if="bigImgUrl.length < 1"
	        >
	          <u-icon name="plus" size="40" color="#000"></u-icon>
		</view>
      <image 
        class="big-img" 
        :src="bigImgUrl" 
        v-if="bigImgUrl" 
        @click="selectBigImg"
      ></image>
    </view>

    <!-- 场景小图上传 -->
    <view class="scene-title">场景</view>
	<text class="tip">其他精彩布置或者设施图片，最多不超过10张</text>
    <view class="small-imgs-upload">
      <view 
        class="small-img-item" 
        v-for="(img, index) in smallImgs" 
        :key="index"
      >
        <image 
          class="small-img" 
          :src="img.imageurl" 
          @click="editSmallImg(index)"
        ></image>
      </view>
      <view 
        class="add-small-img" 
        @click="addSmallImg"
        v-if="smallImgs.length < 10"
      >
        <u-icon name="plus" size="40" color="#000"></u-icon>
      </view>
    </view>
    

<!-- 新增：活动所属类型标签（多选） -->
    <view class="tags-section">
      <view class="scene-title">活动所属类型</view>
      <view class="tags-container">
        <view 
          class="tag-item" 
          v-for="(tag, index) in allTags" 
          :key="index"
          @click="toggleTagSelection(index)"
          :class="{ 'tag-selected': selectedTags.includes(tag) }"
        >
          {{ tag }}
        </view>
      </view>
    </view>

    <!-- 活动内容描述 -->
    <view class="content-title">活动内容描述</view>
    <textarea 
      class="content-textarea" 
      v-model="activityContent" 
      placeholder="请输入活动内容描述"
    ></textarea>

    <!-- 其他表单信息 -->
    <view class="form-item">
      <text class="label">活动标题：</text>
      <input class="input" v-model="eventtitle" placeholder="请输入醒目的标题" />
    </view>
    <view class="form-item">
      <text class="label">地点：</text>
      <input class="input" v-model="location" placeholder="请输入地点" />
    </view>
    
	<view class="form-item date-item">
	    <!-- 标签 -->
	    <view class="form-label">日期段：</view>
	    
	    <!-- 日期选择区域（开始+结束日期） -->
	    <view class="date-range">
	      <!-- 开始日期选择器 -->
	      <view class="date-picker">
	        <view class="picker-label">开始日期：</view>
	        <picker 
	          mode="date" 
	          :value="startDate" 
	          start="2023-01-01" 
	          end="2025-12-31"
	          @change="onStartDateChange"
	          class="picker-display"
	        >
	          {{ formatDate(startDate) || '请选择' }}
	        </picker>
	      </view>
	      
	      <!-- 分割线 -->
	      <view class="date-divider">-</view>
	      
	      <!-- 结束日期选择器 -->
	      <view class="date-picker">
	        <view class="picker-label">结束日期：</view>
	        <picker 
	          mode="date" 
	          :value="endDate" 
	          :start="startDate" 
	          end="2025-12-31"
	          @change="onEndDateChange"
	          class="picker-display"
	        >
	          {{ formatDate(endDate) || '请选择' }}
	        </picker>
	      </view>
	    </view>
	  </view>
	
    <view class="form-item">
      <text class="label">时间段：</text>
      <view>
          <TimeRangeSelector ref="timeRange" />
        </view>
    </view>
    <view class="form-item">
      <text class="label">几人成团：</text>
      <input class="input" v-model="participants" placeholder="请输入数量" />
    </view>
	
	<!-- 二维码容器 -->
	    <view class="qrcode-list">
	      <!-- 微信 -->
	      <view class="qrcode-item">
	        <!-- 图标 -->
	        <view class="payment-icon wechat-icon">
	          <text class="iconfont icon-wechat"></text>
	        </view>
	        
	        <!-- 内容区 -->
	        <view class="qrcode-content">
	          <view class="payment-name">微信群二维码</view>
	          
	          <!-- 二维码图片 -->
	          <view class="qrcode-img-wrap">
	            <image 
	              class="qrcode-img" 
	              :src="wechatImgUrl"
	              @click="selectWechatImg"
	            ></image>
	          </view>
	          
	          <!-- 说明文字 -->
	          <view class="qrcode-desc">
	            <text>1. 微信联系码</text>
	            <text>2. 备注：微信联系桥梁</text>
	          </view>
	        </view>
	      </view>
	      
	      <!-- ali -->
	      <view class="qrcode-item">
	        <view class="payment-icon alipay-icon">
	          <text class="iconfont icon-alipay"></text>
	        </view>
	        
	        <view class="qrcode-content">
	          <view class="payment-name">支付宝群二维码</view>
	          
	          <view class="qrcode-img-wrap">
	            <image 
	              class="qrcode-img"
	              :src="aliImgUrl"
	              @click="selectAliImg"
	            ></image>
	          </view>
	          
	          <view class="qrcode-desc">
	            <text>1. 支付宝联系二维码</text>
	            <text>2. 好友备注：活动报名-姓名</text>
	          </view>
	        </view>
	      </view>
	    </view>

    <!-- 确认提交按钮 -->
    <button class="submit-btn" @click="submitActivity">确认提交</button>
  </view>
</template>

<script>
	// import TimeRangeSelector from '@/components/TimeRangeSelector.vue' 
	import {
		insertEventInfo,
	} from '@/config/api.js'
	
export default {

  data() {
    return {
		eventtitle:'',//活动主题
      bigImgUrl: '', // 大图地址
	  imageurl:'',
      smallImgs: [], // 小图地址列表
      activityContent: '', // 活动内容描述
      sponsor: '', // 发起方
      location: '', // 地点
      startTime: '', // 开始时间
      endTime: '', // 结算时间
      participants: '', // 几人成团数量
	  startDate: '', // 开始日期（格式：yyyy-MM-dd）
	  endDate: '',   // 结束日期（格式：yyyy-MM-dd）
	  
	  // 新增：标签相关
	  allTags: ['公益', '教育', '运动', '艺术', '科技', '寻亲', '文化', '娱乐'], // 所有可选类型标签
	  selectedTags: [], // 选中的标签列表
	  wechatImgUrl:'',//微信二维码
	  aliImgUrl:'',//支付宝二维码
	  timeRanges:[],//时间段
    };
  },
  methods: {
	  submit() {
	        // 获取所有有效时间段
	        const timeRanges = this.$refs.timeRange.getTimeRangeValues();
	        console.log('选中的时间段：', timeRanges);
	        // 提交表单逻辑...
	      },
    goBack() {
      // 返回上一页
      uni.navigateBack();
    },
    selectBigImg() {
      // 选择大图
      uni.chooseImage({
        count: 1,
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
		  console.log(tempFilePath)
          // this.bigImgUrl = tempFilePath;
          // 可在此调用上传图片到后台的方法，将tempFilePath上传
          this.uploadImage(tempFilePath, 'big');
		  console.log(this.bigImgUrl);
        }
      });
    },
    addSmallImg() {
      // 添加小图
      uni.chooseImage({
        count: 1,
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
		  console.log(tempFilePath)
          // 上传小图到后台
          this.uploadImage(tempFilePath, 'small');
		  // this.smallImgs.push(this.imageurl);
		  console.log(this.smallImgs);
        }
      });
    },
    editSmallImg(index) {
      // 编辑小图
      uni.chooseImage({
        count: 1,
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          // 上传修改后的小图到后台
          this.uploadImage(tempFilePath, 'small','edit',index);
		  // this.smallImgs.splice(index, 1, this.imageurl);
		  console.log(this.smallImgs);
        }
      });
    },
	selectWechatImg() {
	  // 选择微信二维码
	  uni.chooseImage({
	    count: 1,
	    sourceType: ['album', 'camera'],
	    success: (res) => {
	      const tempFilePath = res.tempFilePaths[0];
		  console.log(tempFilePath)
	      this.uploadImage(tempFilePath, 'wechat');
		  console.log(this.wechatImgUrl);
	    }
	  });
	},
	selectAliImg() {
	  // 选择支付宝二维码
	  uni.chooseImage({
	    count: 1,
	    sourceType: ['album', 'camera'],
	    success: (res) => {
	      const tempFilePath = res.tempFilePaths[0];
		  console.log(tempFilePath)
	      this.uploadImage(tempFilePath, 'ali');
		  console.log(this.aliImgUrl);
	    }
	  });
	},
    uploadImage(filePath, type,flag,index) {
      // 上传图片到后台的方法
      uni.uploadFile({
        url: uni.$u.http.config.baseURL+'/event/list/uploadImage', // 后台上传接口地址
        filePath: filePath,
        name: 'file',
        formData: {
          'type': type // 区分大图和小图
        },
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data);
          if (data.code === 200) {
            uni.showToast({
              title: '图片上传成功',
              icon: 'success'
            });
			console.log(data);
            // 若后台返回图片存储地址，可在此更新本地图片地址
			this.imageurl= data.url;
			if(flag=='edit'){
				this.smallImgs.splice(index, 1, {"imageurl":data.url,"imagecategory":"small_image"});
				console.log(this.smallImgs);
			}else {
				if(type == 'big'){
					this.bigImgUrl = data.url;
					console.log(this.bigImgUrl);
				} else if(type == 'small') {
					this.smallImgs.push({"imageurl":data.url,"imagecategory":"small_image"});
					console.log(this.smallImgs);
				} else if(type == 'wechat') {
					this.wechatImgUrl=data.url;
					console.log(this.wechatImgUrl);
				} else if(type == 'ali') {
					this.aliImgUrl=data.url;
					console.log(this.aliImgUrl);
				}
			}
           
          } else {
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '网络错误，上传失败',
            icon: 'none'
          });
        }
      });
    },
	// 新增：切换标签选中状态
	    toggleTagSelection(index) {
	      const tag = this.allTags[index];
	      const tagIndex = this.selectedTags.indexOf(tag);
	      
	      if (tagIndex > -1) {
	        // 已选中，取消选择
	        this.selectedTags.splice(tagIndex, 1);
	      } else {
	        // 未选中，添加选择
	        this.selectedTags.push(tag);
	      }
	    },
    async submitActivity() {
		this.timeRanges = this.$refs.timeRange.getTimeRangeValues();
		console.log('选中的时间段：', this.timeRanges);
		
		const {
			data: res
		} = await insertEventInfo({
			initiator:"ZYQ",
			detailedaddress: this.location,
			starttime: this.startDate,
			endtime: this.endDate,
			eventcontent: this.activityContent,
			eventtitle: this.eventtitle,
			location: this.location,
			startTime: this.startDate,
			endTime: this.endDate,
			groupsize: this.participants,
			category: JSON.stringify(this.selectedTags),
			timeperiod: JSON.stringify(this.timeRanges),
			bigImageList:[
				{imageurl:this.bigImgUrl,imagedesc:'大图',imagecategory:"big_image"},
			],
			qrcodeImageList:[
				{imageurl:this.wechatImgUrl,imagedesc:'微信',imagecategory:"qr_image"},
				{imageurl:this.aliImgUrl,imagedesc:'支付宝',imagecategory:"qr_image"}
			],
			imageList:this.smallImgs
		})
		
		// 跳回我的发布活动逻辑
		uni.navigateTo({
		  url: '/other_pages/myPublishedActivities/myPublishedActivities'
		});
     
    },
	
	// 开始日期变化
	    onStartDateChange(e) {
	      this.startDate = e.detail.value;
	      // 若结束日期早于新的开始日期，自动同步结束日期
	      if (this.endDate && this.startDate > this.endDate) {
	        this.endDate = this.startDate;
	      }
	    },
	    // 结束日期变化
	    onEndDateChange(e) {
	      this.endDate = e.detail.value;
	    },
	    // 格式化日期为 "MM月dd日"
	    formatDate(dateStr) {
	      if (!dateStr) return '请选择';
	      const date = new Date(dateStr);
	      const month = date.getMonth() + 1;
	      const day = date.getDate();
	      return `${month}月${day}日`;
	    },
	    // 格式化日期范围为 "MM月dd日 - MM月dd日"
	    formatRange(start, end) {
	      return `${this.formatDate(start)} - ${this.formatDate(end)}`;
	    },
	    // 将 Date 对象转为 yyyy-MM-dd 格式
	    formatDateToYmd(date) {
	      const year = date.getFullYear();
	      const month = String(date.getMonth() + 1).padStart(2, '0');
	      const day = String(date.getDate()).padStart(2, '0');
	      return `${year}-${month}-${day}`;
	    },
		// 预览二维码图片（点击放大查看）
		previewImage(imgUrl) {
		    uni.previewImage({
		        urls: [imgUrl],  // 需要预览的图片链接列表
		        current: imgUrl, // 当前显示图片的链接
		        loop: false      // 是否可循环预览
		    });
		}
  }
};
</script>

<style scoped>
.publish-activity-page {
  background-color: #fff;
  min-height: 100vh;
  padding: 0 24rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1px solid #eee;
}

.back-btn {
  background-color: #fff;
  border: 1px solid #999;
  border-radius: 8rpx;
  padding: 8rpx 16rpx;
  font-size: 28rpx;
  margin-right: 24rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.big-img-upload {
  margin: 12rpx 0;
}

.add-big-img {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
  display: inline-block;
}

.big-img {
  width: 100%;
  height: 400rpx;
  object-fit: cover;
  border: 1px solid #eee;
}

.scene-title,
.content-title {
  font-size: 30rpx;
  font-weight: bold;
  background-color: #00bfff;
  color: #fff;
  padding: 8rpx 16rpx;
  margin: 16rpx 0;
}

.small-imgs-upload {
  display: flex;
  flex-wrap: wrap;
}

.small-img-item {
  width: 120rpx;
  height: 120rpx;
  margin-right: 16rpx;
  margin-bottom: 16rpx;
}

.small-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border: 1px solid #eee;
}

.add-small-img {
  width: 120rpx;
  height: 120rpx;
  border: 1px dashed #999;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}

/* 新增：标签样式 */
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  padding: 10rpx 0;
}

.tag-item {
  padding: 10rpx 20rpx;
  border: 2rpx solid #ccc;
  border-radius: 20rpx;
  font-size: 26rpx;
  background-color: #f5f5f5;
  cursor: pointer;
}

.tag-selected {
  border-color: #007AFF;
  background-color: #e8f4ff;
  color: #007AFF;
  font-weight: 500;
}

.content-textarea {
  width: 100%;
  min-height: 200rpx;
  border: 1px solid #eee;
  padding: 16rpx;
  margin-bottom: 24rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.label {
  font-size: 28rpx;
  width: 120rpx;
}

.input {
  flex: 1;
  height: 60rpx;
  border: 1px solid #eee;
  padding: 0 16rpx;
}

.submit-btn {
  background-color: #007AFF;
  color: #fff;
  font-size: 30rpx;
  padding: 20rpx;
  width: 100%;
  margin: 40rpx 0;
  border-radius: 8rpx;
}

/* 整体表单项布局 */
/* .form-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 24rpx;
} */

.form-label {
  width: 120rpx;
  font-size: 28rpx;
  color: #333;
  margin-right: 16rpx;
  display: flex;
  align-items: center;
}

/* 日期段专属样式 */
.date-item .date-range {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8rpx;
  overflow: hidden;
}

.date-picker {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16rpx;
}

.date-picker .picker-label {
  width: auto;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.picker-display {
  width: 100%;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 26rpx;
  color: #333;
  border: 1px solid #eee;
  border-radius: 6rpx;
  padding: 0 16rpx;
  box-sizing: border-box;
}

.date-divider {
  font-size: 28rpx;
  color: #999;
  margin: 0 16rpx;
}

.qrcode-list {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.qrcode-item {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
}

.payment-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  margin-top: 5rpx;
}

.wechat-icon {
  background-color: #07c160;
  color: #fff;
}

.alipay-icon {
  background-color: #1677ff;
  color: #fff;
}

.qrcode-content {
  flex: 1;
}

.payment-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 15rpx;
}

.qrcode-img-wrap {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 15rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 10rpx;
  box-sizing: border-box;
}

.qrcode-img {
  width: 100%;
  height: 100%;
}

.qrcode-desc {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

/* 点击图片时的反馈效果 */
.qrcode-img-wrap:active {
  opacity: 0.9;
  transform: scale(0.98);
  transition: all 0.2s;
}


</style>